package com.ytjj.common.utils.locker;

import org.redisson.api.RCountDownLatch;
import org.redisson.api.RLock;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**

 @since 2021年9月3日16:39:25
 */
@Component("distributedLocker")
public class RedisDistributedLocker implements DistributedLocker {

    @Resource
    private RedissonClient redissonClient;

    /**
     加锁
     @param lockKey 锁key
     @return RLock
     */
    @Override
    public RLock lock(String lockKey) {
        RLock rLock = redissonClient.getLock(lockKey);
        rLock.lock();
        return rLock;
    }

    /**
     加锁，并设置解锁时间
     @param lockKey 锁key
     @param leaseTime 上锁以后leaseTime秒自动解锁时间
     @return RLock
     */
    @Override
    public RLock lock(String lockKey, int leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(leaseTime, TimeUnit.SECONDS);
        return lock;
    }

    /**
     加锁，并设置等待时间
     @param lockKey 锁key
     @param unit 时间单位
     @param timeout 等待时间
     @return RLock
     */
    @Override
    public RLock lock(String lockKey, TimeUnit unit, int timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(timeout, unit);
        return lock;
    }

    /**
     加锁，并设置等待时间和解锁时间
     @param lockKey 锁key
     @param unit 时间单位
     @param waitTime 等待时间
     @param leaseTime 上锁以后leaseTime秒自动解锁时间
     @return boolean
     */
    @Override
    public boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
        RLock rLock = redissonClient.getLock(lockKey);
        // 尝试加锁，最多等待x秒，上锁以后y秒自动解锁
        try {
            return rLock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            return false;
        }
    }

    /**
     解锁
     @param lockKey 锁key
     */
    @Override
    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.unlock();
    }

    /**
     解锁
     @param lock 锁对象
     */
    @Override
    public void unlock(RLock lock) {
        lock.unlock();
    }

    /**
     获取计数器
     @param lockKey 锁key
     @return RSemaphore
     */
    @Override
    public RSemaphore getSemaphore(String lockKey) {
        RSemaphore semaphore = redissonClient.getSemaphore(lockKey);
        semaphore.tryAcquire();
        return semaphore;
    }

    /**
     获取信号量
     @param lockKey 锁key
     @return RCountDownLatch
     */
    @Override
    public RCountDownLatch getCountDownLatch(String lockKey) {
        RCountDownLatch countDownLatch = redissonClient.getCountDownLatch(lockKey);
        countDownLatch.countDown();
        return countDownLatch;
    }

}
